const { QNConsts } = requirePlugin('QNBleApi');
function sealGenderParam(gender) {
  if (['male', 1, '1'].includes(gender)) {
    return 1;
  }

  return 0;
}

function formatDate(date) {
  if (date instanceof Date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return `${year}-${month}-${day}`;
  }
  return date;
}

/**
 *
 * @param {*} obj
 * @param {*} encode
 * @returns
 */
function objToStr(obj, encode = false) {
  let str = '';
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (encode) {
        str += `&${key}=${encodeURIComponent(obj[key])}`;
      } else {
        str += `&${key}=${obj[key]}`;
      }
    }
  }

  return str.slice(1);
}

function getFullYear(date) {
  return new Date(
    new Date(typeof date === 'string' ? date.replace(/-/g, '/') : date),
  ).getFullYear();
}

/**
 * 判断是否是目标设备
 * @param {string[] | stirng} targetDeviceType 目标设备类型
 * @param {string} deviceType 设备类型
 */
function isTargetDevice(targetDeviceType, deviceType) {
  return Array.isArray(targetDeviceType)
    ? targetDeviceType.includes(deviceType)
    : targetDeviceType === deviceType;
}

/**
 * 判断是否是八电级有效数据
 * @param {*} scaleData
 */
function isValidEightMeasure(scaleData) {
  // 判断是否是目标设备
  let flag = isTargetDevice(
    [
      QNConsts.QNBleDeviceType.WSP_EIGHT_DUAL_MODE_SCALE,
      QNConsts.QNBleDeviceType.SINGLE_BLE_EIGHT_SCALE,
      QNConsts.QNBleDeviceType.SINGLE_BLE_USER_EIGHT_SCALE,
    ],
    scaleData.device.type,
  );

  // 判断指标是否存在
  if (flag) {
    const validKeys = [
      'muscleRh',
      'muscleLh',
      'muscleRf',
      'muscleLf',
      'muscleT',
      'fatRh',
      'fatLh',
      'fatRf',
      'fatLf',
      'fatT',
    ];
    validKeys.forEach((key) => {
      if (!scaleData[key]) {
        return false;
      }
    });
    return true;
  }
  return false
}

function formatTime(date, fmt = 'YYYY-MM-DD HH:mm:ss') {
  if (date.toString() === 'Invalid Date') {
    // console.warn('[formatTime] Invalid Date');
    return '';
  }
  const o = {
    'M+': date.getMonth() + 1,
    'D+': date.getDate(),
    'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
    'H+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    // 季度
    'q+': Math.floor((date.getMonth() + 3) / 3),
  };
  const week = {
    0: '日',
    1: '一',
    2: '二',
    3: '三',
    4: '四',
    5: '五',
    6: '六',
  };

  let dateString = fmt;

  if (/(Y+)/.test(dateString)) {
    dateString = dateString.replace(RegExp.$1, (`${date.getFullYear()}`).substr(4 - RegExp.$1.length));
  }
  if (/(E+)/.test(dateString)) {
    // eslint-disable-next-line no-nested-ternary
    dateString = dateString.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '星期' : '周') : '') + week[date.getDay()]);
  }

  // 毫秒数
  if (/(S)/.test(dateString)) {
    dateString = dateString.replace(RegExp.$1, `${date.getMilliseconds()}`);
  }

  Object.keys(o).forEach((prop) => {
    if (new RegExp(`(${prop})`).test(dateString)) {
      const value = `${o[prop]}`;
      dateString = dateString.replace(RegExp.$1, `00${value}`.substr(value.length));
    }
  });
  return dateString;
}

module.exports = {
  sealGenderParam,
  objToStr,
  formatDate,
  getFullYear,
  isTargetDevice,
  isValidEightMeasure,
  formatTime,
};
